import groovy.json.JsonOutput
import groovy.json.JsonSlurper
import groovy.time.TimeCategory

import java.beans.PropertyChangeListener

/**
 * Created by hzhlu on 2017-02-16.
 */
class MyGroovyClass {
// 官网地址：

    static void main(String[] args) {

        // ObservableMap 应用
        // ------------------------------------------------------------------------------------------------------------
        println "ObservableMap 应用".center(80, "-")
        def om = [a: "123", b: 234, c: 'CC', d: new Date(), e: 1.2] as ObservableMap;
        om._table = "table";
        om._update_fields = [] as Set;
        def listener = { evt ->
            println "table value changed: ${evt.source['_table']}.${evt['propertyName']} from [${evt['oldValue']}] to [${evt['newValue']}] "
            if (evt instanceof ObservableMap.PropertyUpdatedEvent) {
                evt.source._update_fields << evt.propertyName;
            }

        } as PropertyChangeListener
        om.addPropertyChangeListener(listener)

        om['a'] = "124"
        om.b = 4455
        println om
        println om._update_fields

        // 时间
        // ------------------------------------------------------------------------------------------------------------
        println "时间".center(80, "-")
        use(TimeCategory) {
            println 1.minute.from.now
            println 10.hours.ago
            def someDate = new Date()
            println someDate - 3.months
        }

        // 字符串
        // ------------------------------------------------------------------------------------------------------------
        println "字符串".center(80, "-")
        def groovy = "groovy"
        println "hello ${groovy}"
        println "${groovy[0..3]}"
        println "${groovy[-3..-1]}"
        println 'hello ${groovy}'
        println groovy.center(50, "=*")

        def nullObj = "null##11"
        println "safe null: ${nullObj?.toString()}"
        nullObj = null
        println "safe null: ${nullObj?.toString()}"

        // JSON  obj to string
        // ------------------------------------------------------------------------------------------------------------
        println "JSON  obj to string".center(80, "-")
        def map = [k1: 123, k2: "111", k3: "value3", k4: new Date()]
        println "map: ${map['k4']}"
        String jsonStr = JsonOutput.toJson(map)
        println "obj to jsonStr: map: ${map}  ==> ${jsonStr}"
        print "func1（null）: "; println func1(null)
        println "func1: " + func1(map)
        println "after func1 map: " + map

        // JSON  string to obj
        // ------------------------------------------------------------------------------------------------------------
        println "JSON  string to obj".center(80, "-")
        def jsonObj = new JsonSlurper().parseText(jsonStr)
        println "jsonStr to obj: ${jsonObj}"

        def list = [1, 2, 3, 4, '555', new Date()]

        // 反射调用,  hello(Map params)
        // ------------------------------------------------------------------------------------------------------------
        println "反射调用".center(80, "-")
        String className = "hello.HelloGroovy"
        String methodName = "funcHello"
        def clzz = Class.forName(className).newInstance()
        def ret = clzz."${methodName}"(map);
        println "reflect call " + ret

        try {
            /* ... */
        } catch (IOException | NullPointerException e) {
            /* one block to handle 2 exceptions */
        }
//        def value = "groovy"
//        def value = 31
//        def value = 2

        // switch
        // ------------------------------------------------------------------------------------------------------------
        println "switch".center(80, "-")
        def value = '0400/12'
        switch (value) {
            case 'groovy':
                println "gro!"
                break;
            case 1..10:
                println "123"
                break;
            case [31, 42, 53, 64]:
                println "数组"
                break;
            case ~/0400\/\d{2}/:
                println "Reg表达式"
                break;
            default:
                println("没找到")
        }

        // 写文件
        // ------------------------------------------------------------------------------------------------------------
        println "写文件".center(80, "-")
        File file = new File("filename");
        println "write to file ==>  ${file.absolutePath}"
        def writer = file.newPrintWriter("UTF-8");

        //循环
        // ------------------------------------------------------------------------------------------------------------
        println "循环".center(80, "-")
        3.times { it ->
            writer << "第 ${it} 行|v1|v2|" + System.currentTimeMillis() << "\n"
        }
        5.upto(7) { it ->
            writer << "第 ${it} 行|v3|v4|" + System.currentTimeMillis() << "\n"
        }

        (9..11).each { it ->
            writer << "第 ${it} 行|v5|v6|" + System.currentTimeMillis() << "\n"
        }
        writer.flush()
        writer.close()

        // 读文件1
        // ------------------------------------------------------------------------------------------------------------
        println("读文件1".padLeft(50, "="))
        file.readLines().each { line ->
            println line
        }

        // 读文件2
        // ------------------------------------------------------------------------------------------------------------
        println("读文件2".padRight(50, "+"))
        file.splitEachLine "\\|", 'UTF-8', { line ->
            println line
            line.each {
                println it
            }
        }


    }


    static func1(map) {
        println map
        map?.kx = 112233
    }

    def func2() {
        println map
        map?.ky = 'ffvvdd'

    }

    def wrapping(data, table) {
        if (data == null || data instanceof ObservableMap) {
            return data;
        } else {
//            def om = new ObservableMap(data);
            def om = [a: "123", b: 234, c: 'CC', d: new Date(), e: 1.2] as ObservableMap;
            om._table = table;
            om._update_fields = [] as Set;

            // FIXED 1.8中可用，但2.x中失败，对应审核数据库中的变化
            def listener = { evt ->
                if (evt instanceof ObservableMap.PropertyUpdatedEvent) {
                    evt.source['_update_fields'] = evt.propertyName
                }
            } as PropertyChangeListener

            om.addPropertyChangeListener(listener)

//            om.addPropertyChangeListener({ evt ->
//                // if (evt.type==evt.UPDATED) evt.source._update_fields << evt.propertyName;
//                if (evt instanceof ObservableMap.PropertyUpdatedEvent) {
//                    // evt.source._update_fields << evt.propertyName;
//                    evt.source['_update_fields'] = evt.propertyName;
//                }
//            } as PropertyChangeListener);

            return om;
        }
    }
    /**
     * 更新交易信息
     *
     * @param data
     * @param log
     * @return
     */
    def updateByOM(data) {
        if (!data || !data._table) return false;
        if (!data._update_fields) return true;
        def params = [];
        String updateSql = "update ${data._table} set ";
        for (String field in data._update_fields) {
            if (data[field] != null) {
                updateSql += (params ? ', ' : '') + " $field = ?";
                params << data[field];
            }
        }
        updateSql += '\n where id = ?'
        params << data.id

        println "updateByOM sql:\n$updateSql\nparams: $params"

//        1 == db.executeUpdate(updateSql, params)
    }


}
